package com.xcb.my.controller;

import java.net.URLDecoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.plat.controller.OnlineController;



@Controller
public class UserController  extends OnlineController {
	private static Logger log = Logger.getLogger(UserController.class);	
	
	@RequestMapping(
			value="/User.do",
			method=RequestMethod.POST,
			produces="application/json;charset=" + ENCODING)
	public void inQR (
			@RequestBody String reqMsg,
			HttpServletRequest request,
			HttpServletResponse response
	) {
		MSG_CFG = "BUSI_USER.xml";
		
		log.debug("/BUSI_USER.xml");
		run(reqMsg, request, response);
	}


	/**
	 * @Func	isLegalReqMsg
	 * @Brief	是否时合法报文
	 */
	@Override
	protected boolean judgeReqAdd(HttpServletRequest request) {
		return true;
	}

	/**
	 * @Func	getReqMsg
	 * @Brief	获取请求报文
	 */
	@Override
	protected boolean judgeReqMsg(byte[] msg) {
		try {
			@SuppressWarnings("deprecation")
			String strInMsg = URLDecoder.decode(new String(msg));
			log.info("HTTP请求 接受报文：\n"+ strInMsg);
	
			JSONObject jsonData= JSONObject.fromObject(strInMsg);
			jsonData.toString().getBytes();
		} catch (Exception e) {
			log.error("解析http参数为json出错：" + e);
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * @Func	getErrorMsg
	 * @Brief	获取异常报文
	 */
	@Override
	protected byte[] getErrorMsg(String errorCode, String errorMsg) {
		Map<String, String> rspMap = new HashedMap();
		rspMap.put("RspCode", errorCode);
		rspMap.put("RspMsg", errorMsg);
		
		return JSONObject.fromObject(rspMap).toString().getBytes();
	}

	/**
	 * @Func	getReqMsg
	 * @Brief	获取请求报文
	 */
	@Override
	protected byte[] getReqMsg(String msg) {
		try {
			byte[] msgIn = null;
			
			String strInMsg = URLDecoder.decode(msg, ENCODING);
			log.info("HTTP请求 接受报文：\n"+ strInMsg);

			JSONObject jsonData= JSONObject.fromObject(strInMsg);
			msgIn = jsonData.toString().getBytes();

			if(isLegalReqMsg(msgIn)) {
				return msgIn;
			} else {
				return null;
			}
		} catch (Exception e) {
			log.error("解析http参数为json出错：" + e);
			e.printStackTrace();
			return null;
		}
	}
}
